<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 深圳市中南网络科技有限公司 [ http://www.znwlsz.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.znwlsz.com
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\common\builder\ZBuilder;
use app\common\model\User as U;
use think\Db;
/**
 * 辅食控制器
 * @package app\admin\controller
 */
class Jieguo extends Admin
{
 
    public function gerendaochu($id){
        $list = U::field('username,defen,datishijian')
            ->order('defen desc,datishijian asc')
            ->select();

        $this->exportExcel('defen.xlsx',$list,'个人得分表',['1'=>'username','2'=>'defen','3'=>'datishijian']);
    }

    public function tuanduidaochu($id){
        $list = U::field('id,fenzu,sum(defen) as zonfen,sum(datishijian) as zonshichang')
            ->group('fenzu')
            ->order('zonfen desc,zonshichang asc')
            ->select();

        $this->exportExcel('tuanduidaochu.xlsx',$list,'团队得分表',['1'=>'fenzu','2'=>'zonfen','3'=>'zonshichang']);

    }

    function exportExcel($template,$list,$filename,$indexKey=array()){  
    require '../extend/PHPExcel/PHPExcel.php';
      
    $header_arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');  
      
    //$objPHPExcel = new PHPExcel();                        //初始化PHPExcel(),不使用模板  
    $objPHPExcel = \PHPExcel_IOFactory::load($template);     //加载excel文件,设置模板  
      
    $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);  //设置保存版本格式  
      
    //接下来就是写数据到表格里面去  
    $objActSheet = $objPHPExcel->getActiveSheet();  
    $objActSheet->setCellValue('A2',  "活动名称：知识竞赛");  
    $objActSheet->setCellValue('C2',  "导出时间：".date('Y-m-d H:i:s'));  
    $i = 4;  
    $paiming = 1;
    foreach ($list as $row) { 

        $objActSheet->setCellValue('A'.$i,$paiming);  

        foreach ($indexKey as $key => $value){  
            //这里是设置单元格的内容  
            $objActSheet->setCellValue($header_arr[$key].$i,$row[$value]);  
        }  

        $i++;  
        $paiming++;
    }  
      
    // 1.保存至本地Excel表格  
    //$objWriter->save($filename.'.xls');  
      
    // 2.接下来当然是下载这个表格了，在浏览器输出就好了  
    header("Pragma: public");  
    header("Expires: 0");  
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
    header("Content-Type:application/force-download");  
    header("Content-Type:application/vnd.ms-execl");  
    header("Content-Type:application/octet-stream");  
    header("Content-Type:application/download");;  
    header('Content-Disposition:attachment;filename="'.$filename.'.xls"');  
    header("Content-Transfer-Encoding:binary");  
    $objWriter->save('php://output');  
}
    public function downloadWord($content, $fileName='new_file.doc'){
        if(empty($content)){
            return false;
        }
        
        header("Content-type:text/html;charset=utf-8");
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=个人答题明细.doc");
    
        $html = '<html xmlns:v="urn:schemas-microsoft-com:vml"
             xmlns:o="urn:schemas-microsoft-com:office:office"
             xmlns:w="urn:schemas-microsoft-com:office:word" 
             xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" 
             xmlns="http://www.w3.org/TR/REC-html40">';
        $html .= '<head><meta charset="UTF-8" /></head>';

        echo $html . '<body>'.$content .'</body></html>';
    }

    public function outword($id){
        $exam = Db::name('exam')->where('user_id',$id)->find();
        if(empty($exam))$this->error('暂无数据');

        $html = $this->defendetail($id);

        $html = htmlspecialchars_decode($html);
        $this->downloadWord($html,input('note').'.doc');
    }
    public function geren()
    {
        $data_list = U::where($this->getMap())
            ->field('username,id,phone,defen,datishijian')
            ->order('defen desc,datishijian asc')
            ->select();
        $daochu_access = [
            'title' => '导出所有人得分excel',
            'icon'  => 'fa fa-fw fa-file-excel-o',
            'href'  => url('jieguo/gerendaochu',['id'=>'__id__'])
        ];

        $btn_access = [
            'title' => '查看得分详情',
            'icon'  => 'fa fa-fw fa-user',
            'href'  => url('jieguo/defendetail',['id'=>'__id__'])
        ];

        $outword = [
            'title' => '导出答题明细',
            'icon'  => 'fa fa-fw fa-user',
            'href'  => url('jieguo/outword',['id'=>'__id__'])
        ];

        return ZBuilder::make('table')
            ->setSearch(['username' => '姓名']) // 设置搜索参数
            ->addColumns([
                ['__INDEX__', '排名'],
                ['username', '姓名'],
                ['phone', '手机号码'],
                ['defen','得分'],
                ['datishijian','用时'],
                ['right_button', '操作', 'btn'],
            ])
            ->setTableName('user')
            ->addTopButton('custom', $daochu_access) // 添加顶部按钮
            ->addRightButton('custom', $btn_access,true, ['title' => true, 'icon' => false])
            ->addRightButton('custom', $outword,false, ['title' => true, 'icon' => false])
            ->setRowList($data_list)
            ->fetch();
    }

    public function index()
    {
        $data_list = U::where($this->getMap())
            ->field('id,fenzu,sum(defen) as zonfen,sum(datishijian) as zonshichang')
            ->group('fenzu')
            ->order('zonfen desc,zonshichang asc')
            ->select();
        
        $btn_access = [
            'title' => '查看该分组',
            'icon'  => 'fa fa-fw fa-user',
            'href'  => url('jieguo/detail',['fenzu'=>'__fenzu__'])
        ];

        $daochu_access = [
            'title' => '导出团队得分excel',
            'icon'  => 'fa fa-fw fa-file-excel-o',
            'href'  => url('jieguo/tuanduidaochu',['id'=>'__id__'])
        ];

        return ZBuilder::make('table')
            ->setSearch(['fenzu' => '分组名称']) // 设置搜索参数
            ->addColumns([
                ['__INDEX__', '排名'],
                ['fenzu', '分组名称'],
                ['zonfen','总分'],
                ['zonshichang','总用时'],
                ['right_button', '操作', 'btn'],
            ])
            ->setTableName('user')
            ->addRightButton('custom', $btn_access,true, ['title' => true, 'icon' => false])
            ->addTopButton('custom', $daochu_access) // 添加顶部按钮
            ->setRowList($data_list)
            ->fetch();
    }

    public function detail($fenzu){
        $data_list = U::where('fenzu',$fenzu)
            ->field('id,fenzu,defen,datishijian,username')
            ->order('defen desc,datishijian asc')
            ->select();
        
        $btn_access = [
            'title' => '查看得分详情',
            'icon'  => 'fa fa-fw fa-user',
            'href'  => url('jieguo/defendetail',['id'=>'__id__'])
        ];

        return ZBuilder::make('table')
            ->addColumns([
                ['username', '姓名'],
                ['defen','总分'],
                ['datishijian','答题用时'],
                ['right_button', '操作', 'btn'],
            ])
            ->setTableName('user')
            ->addRightButton('custom', $btn_access,true, ['title' => true, 'icon' => false])
            
           
            ->setRowList($data_list)
            ->fetch();
    }

    public function defendetail($id){
        $ss = [['id'=>11,'tijiao'=>'0'],['id'=>9,'tijiao'=>'["A","B"]'],['id'=>7,'tijiao'=>'A'],['id'=>15,'tijiao'=>'["A","B","C","D"]']];
      
        $exam = Db::name('exam')->where('user_id',$id)->find();

        $html = '<div style="padding:20px;"></div><div style="padding:20px 50px;" class="test"><h1>得分：'.$exam['defen'].'(用时：'.$exam['datishijian'].')</h1>';
    
        $exam = json_decode($exam['exam'],true);
        if(empty($exam)){
            $this->error('还没查询到考试结果');
        }

        $i = 1;
        foreach ($exam as $key => $value) {
            $vv = Db::name('shiti')->where('id',$value['id'])->find();
            $html .= '<h3>'.$i.' : '.$vv['ctitle'].'</h3>';
            $i++;
            $html .= '<ul style="padding:10px;list-style-type: none;">';

            //选项和答案
            if($vv['type']=='1'){

                $html .= '<li style="padding:10px;">A:'.$vv['A'].'</li>';//选项
                $html .= '<li style="padding:10px;">B:'.$vv['B'].'</li>';//选项
                $html .= '<li style="padding:10px;">C:'.$vv['C'].'</li>';//选项
                $html .= '<li style="padding:10px;">D:'.$vv['D'].'</li>';//选项

                $html .= '<li>正确答案：'.$vv['answer'].'</li></br>';

            }else if ($vv['type']=='2') {

                $html .= '<li style="padding:10px;">A:'.$vv['A'].'</li>';//选项
                $html .= '<li style="padding:10px;">B:'.$vv['B'].'</li>';//选项
                $html .= '<li style="padding:10px;">C:'.$vv['C'].'</li>';//选项
                $html .= '<li style="padding:10px;">D:'.$vv['D'].'</li>';//选项

                $zhengque = json_decode($vv['answer'],true);
                $zhengque = implode('', $zhengque);
                $html .= '<li>正确答案：'.$zhengque.'</li></br>';

                # code...
            }else{
                if($vv['answer']==0){
                    $zhengque = '对';
                }else{
                    $zhengque = '错';
                }
                $html .= '<li>正确答案：'.$zhengque.'</li></br>';
            }
            //选项和答案

            //得分情况
            if($vv['answer']==$value['tijiao']){
                if($vv['type']=='1'){
                    $defen = 1;
                }else{
                    $defen = 2;
                }
            }else{
                $defen = 0;
            }

            //提交的答案和
            if($vv['type']=='2'){
                $tijiao = json_decode($value['tijiao'],true);
                $tijiao = implode('', $tijiao);

                $html .= '<li>提交的答案：'.$tijiao.' 得分(<b>'.$defen.'</b>)</li>';
            }else if ($vv['type']=='3') {
                if($value['tijiao']==0){
                    $tijiao = '对';
                }else{
                    $tijiao = '错';
                }
                $html .= '<li>提交的答案：'.$tijiao.' 得分(<b>'.$defen.'</b>)</li>';
            }else{
                $html .= '<li>提交的答案：'.$value['tijiao'].' 得分(<b>'.$defen.'</b>)</li>';
            }
            
            
            

            $html .= '</ul>';
        }
        $html .= '</div>';
        return $html;
    }

}